package com.dctp.common.manager;

import com.dctp.common.core.RedisManager;
import com.jfinal.plugin.activerecord.Db;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

import com.jfinal.plugin.activerecord.Record;
import java.util.concurrent.ConcurrentHashMap;

public class OrderCacheManager {

    // ✅ symbol -> List<Record>
    private static final Map<String, List<Record>> localCache = new ConcurrentHashMap<>();
    private static final Logger logger = LoggerFactory.getLogger(OrderCacheManager.class);

    /** ✅ 初始化（系统启动时全量加载） */
    public static void initCache() {

        Set<Integer> myShards = ShardManager.getMyShards();
        if (myShards.isEmpty()) {
            logger.warn("当前服务器没有分配任何 shard，不执行盈亏计算");
            return;
        }

        // ✅ 拼接 SQL 占位符
        String shardPlaceholders = ShardManager.buildShardInClause();
        String sql = "SELECT * FROM dctp_order WHERE status = 1 AND shard_id IN (" + shardPlaceholders + ")";

        // ✅ 查询只属于当前服务器的订单
        List<Object> params = new ArrayList<>();
        params.addAll(myShards);
        List<Record> allOrders = Db.find(sql,params.toArray());
        if (allOrders.isEmpty()) return;

        for (Record order : allOrders) {
            localCache.computeIfAbsent(order.getStr("symbol"),
                    k -> new ArrayList<>()).add(order);
        }
        logger.info("✅ 全量订单缓存初始化完成，共 {} 条", allOrders.size());
    }

    /** ✅ 添加或更新订单 */
    public static void addToCache(Record order) {
        String symbol = order.getStr("symbol");
        List<Record> orders = localCache.computeIfAbsent(symbol, k -> Collections.synchronizedList(new ArrayList<>()));

        // ✅ 如果订单已存在，替换
        for (int i = 0; i < orders.size(); i++) {
            if (orders.get(i).getLong("id").equals(order.getLong("id"))) {
                orders.set(i, order);
                return;
            }
        }
        // ✅ 不存在就添加
        orders.add(order);
    }

    /** ✅ 删除订单 */
    public static void removeFromCache(String symbol, Long orderId) {
        List<Record> orders = localCache.get(symbol);
        if (orders != null) {
            orders.removeIf(order -> order.getLong("id").equals(orderId));
        }
    }

    /** ✅ 查询缓存 */
    public static List<Record> getOrdersBySymbol(String symbol) {
        return new ArrayList<>(localCache.getOrDefault(symbol, Collections.emptyList()));
    }
}
